package com.yunchuang.controller.fileinfo;

import cn.hutool.core.lang.UUID;
import com.yunchuang.common.ResultUtil;
import com.yunchuang.model.dto.FileInfoQueryDto;
import com.yunchuang.model.pojo.User;
import com.yunchuang.utils.JSONUtils;
import com.yunchuang.utils.ProfileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.net.URLEncoder;

@WebServlet("/downloadFiles")
public class FileDownloadServlet extends HttpServlet {
    private final Logger logger = LoggerFactory.getLogger("logback");

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        User sessionUser = (User) session.getAttribute("user");
        if (sessionUser == null) {
            JSONUtils.writeOutJSON(ResultUtil.error("用户未登录，请登录后再下载"), resp);
            return;
        }
        req.setCharacterEncoding("utf-8");
        BufferedReader reader = req.getReader();
        String jsonStr = reader.readLine();
        FileInfoQueryDto fileInfo = JSONUtils.jsonToObject(jsonStr, FileInfoQueryDto.class);

        String fileName = fileInfo.getFileName();
        // 原始路径
        String servicePath = ProfileUtils.getServerContext() + File.separator + fileName;

        // 截取文件后缀
        int lastIndexOf = fileName.lastIndexOf(".");
        String substring = fileName.substring(lastIndexOf);

        UUID uuid = UUID.randomUUID();
        String clientPath = ProfileUtils.getContext() + File.separator + uuid + substring;

        // 下载文件
        FileInputStream fis = new FileInputStream(servicePath);
        FileOutputStream fos = new FileOutputStream(clientPath);

        fis.transferTo(fos);

        fis.close();
        fos.close();
        JSONUtils.writeOutJSON(ResultUtil.success("下载成功", null), resp);
    }
}
